package convertstream;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

/**
 *  OutputStreamWriter类:
 *      public OutputStreamWriter(OutputStream out, Charset cs):可以指定输出流(写入)使用的码表
 *  乱码产生的原因,读操作和写操作使用的码表不一样,解决方案(保持码表一致)
 *
 *  FileWriter类(以下两个方法需要JDK11及以上版本才能使用):
 *      public FileWriter(File file, Charset charset) throws IOExceptionL:可以手动指定将来写数据的码表
 *      public FileWriter(File file, Charset charset, boolean append) throws IOException:可以手动指定将来写数据的码表
 *      并且可以对文件进行续写
 *
 *  FileWriter原理:
 *   public FileWriter(String fileName) throws IOException {
 *           super(new FileOutputStream(fileName));
 *       }
 *       public OutputStreamWriter(OutputStream out) {
 *           super(out);
 *       }
 *     通过FileWriter的构造方法,我们会发现 字符输出流 = 字节输出流 + 字符输出转换流(将要写入的字符按照转换流中的码表转换成字节
 *        ,不指定码表的话默认使用的是UTF-8)
 *      之前new FileWriter("1.txt") => new OutputStreamWriter(new FileOutputStream("1.txt")))
 */
public class ConvertStreamDemo01 {
    public static void main(String[] args)throws Exception {
        //method01();
        //method02();
        FileWriter fw = new FileWriter("day23-IO-02/GBK03.txt"
                , Charset.forName("GBK")
                , true);//该方法底层使用其实是super(new FileOutputStream(fileName, append), charset);
        //相当于调用了OutStreamWriter的构造方法:  OutputStreamWriter(OutputStream out, Charset cs)
        //最终就相当于该代码: new OutputStreamWriter(new FileOutputStream(fileName, append),charset)

        fw.write("你好");
        fw.close();
    }

    private static void method02() throws IOException {
        //FileOutputStream fos = new FileOutputStream("day23-IO-01/GBK_02.txt", true);
        //OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("day23-IO-02/GBK02.txt", true)
                , "GBK");
        osw.write("你好");
        osw.close();
    }


    private static void method01() throws IOException {
        //1.关联GBK.txt,将来向GBK.txt中续写内容
        FileWriter fw = new FileWriter("day23-IO-02/GBK.txt",true);

        fw.write("你好");

        fw.close();
    }
}
